# -*- coding:utf-8 -*-
"""
@Time : 2025/02/11 20:25 PM
@Author: xiaomi
@Des: 短信SMS
"""


# 系统包
from fastapi import Request, APIRouter, Query, Security
from core.Auth import check_permissions
from core.Response import fail, success
from core.Utils import code_number
from models.base import User

router = APIRouter()


@router.get('/modify/send', dependencies=[Security(check_permissions)], summary="发送验证码", description='手机号修改')
async def send_msg(req: Request, phone_number: str = Query(..., pattern="^1[34567890]\\d{9}$")):
    """
    修改手机号验证码发送
    :param req:
    :param phone_number:
    :return:
    """
    # redis 连接
    redis = req.app.state.cache
    # 查询当前手机号是否绑定用户
    user = await User.get_or_none(user_phone=phone_number)
    if user:
        return fail(msg=f"手机号 {phone_number} 已被其他用户绑定!")

    # 验证码过期时间
    expire = 10
    # 查询是否发送过验证码
    is_send = await redis.get(name=f"code_{phone_number}")
    if is_send:
        return fail(msg=f"手机号 {phone_number} 已发送过验证码，若未收到短信，请{expire}分钟后重试!")

    # 生成验证码
    # code = code_number(6)
    code = '123456'

    await redis.set(name=f"code_{phone_number}", value=code, ex=expire * 60)
    return success(msg=f"短信已经发送，{expire} 分钟内有效。", data=expire * 60)


@router.get('/send', summary="发送验证码", description='注册、登陆')
async def send_msg(req: Request, phone_number: str = Query(..., pattern="^1[34567890]\\d{9}$")):
    """
    验证码发送
    :param req:
    :param phone_number:
    :return:
    """
    # redis 连接
    redis = await req.app.state.cache
    # 查询当前手机号是否绑定用户
    user = await User.get_or_none(user_phone=phone_number)
    if not user:
        return fail(msg=f"手机号 {phone_number} 未绑定用户!")

    # 验证码过期时间
    expire = 10
    # 查询是否发送过验证码
    is_send = await redis.get(name=f"code_{phone_number}")
    if is_send:
        return fail(msg=f"手机号 {phone_number} 已发送过验证码，若未收到短信，请{expire}分钟后重试!")

    # 生成验证码
    # code = code_number(6)
    code = '123456'

    await redis.set(name=f"code_{phone_number}", value=code, ex=expire * 60)
    return success(msg=f"短信已经发送，{expire} 分钟内有效。", data=expire * 60)


async def check_code(req: Request, verify_code: str, phone: str):
    """
    短信验证码校验
    :param req:
    :param verify_code:
    :param phone:
    :return:
    """
    # 获取redis中的验证码
    redis = req.app.state.cache
    code = await redis.get(f"code_{phone}")
    # 比对验证码
    if code and verify_code == code:
        await redis.delete(f"code_{phone}")
        return True
    # 获取缓存中验证码
    return False